package com.tfswx.ocrengine.executor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.ocrengine.dto.OcrOutputDTO;
import com.tfswx.ocrengine.exception.AppException;
import com.tfswx.ocrengine.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Ricky
 * @date 2021/1/11
 */
@Slf4j
public class HanWangOcrExecutor extends AbstractOcrExecutor {

    private static final String SUCC_CODE = "000000";

    @Override
    public OcrOutputDTO run(String wjnr) {
        setHost("http://182.48.109.23:10003/ofs/api/sync/v2/6001");

        String appId = "4ce59352fd2e4246a72b864c133e9751";
        String appKey = "2c602d0c30ae4c3db40c8e4b4b61b5fe";
        long timestamp = System.currentTimeMillis();
        String key = appKey + timestamp;
        String checksum = DigestUtils.md5Hex(key);

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        MediaType acceptType = MediaType.APPLICATION_JSON;
        // 设置请求的格式类型
        headers.setContentType(type);

        List<MediaType> acceptableMediaTypes = new ArrayList<>();
        acceptableMediaTypes.add(acceptType);
        headers.setAccept(acceptableMediaTypes);

        headers.add("Authorization", "AppId " + appId);
        headers.add("X-Timestamp", String.valueOf(timestamp));
        headers.add("X-Checksum", checksum);

        FileSystemResource fileSystemResource = new FileSystemResource("E:\\Users\\Ricky\\Desktop\\pdf\\300.png");
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("fileId", System.currentTimeMillis());
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        long startTime = System.currentTimeMillis();
        JSONObject response = HttpUtil.postForObject(getHost(), files, JSONObject.class);
        log.info("耗时：" + (System.currentTimeMillis() - startTime));

        String code = response.getString("code");
        if (!SUCC_CODE.equals(code)) {
            throw new AppException(response.getString("message"));
        }
        JSONObject data = response.getJSONObject("data");

        //        JSONArray contents = data.getJSONArray("contents");
        try {
            FileUtils.writeStringToFile(new File("hanwang.json"), JSON.toJSONString(data, true), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        /// 代码测试
        //        JSONObject stateJsonObj = response.getJSONObject("state");
        //        int code = stateJsonObj.getIntValue("code");
        //        boolean success = stateJsonObj.getBooleanValue("success");
        //        int ok = stateJsonObj.getIntValue("ok");
        //        if (code == 0 && success && ok == 1) {
        //            // 识别成功
        //            JSONObject jsonObject = ConvertOcrDataUtils.convertXf2Ali(response);
        //
        //            List<JSONObject> allOcrFileResult = new ArrayList<>();
        //            allOcrFileResult.add(jsonObject);
        //            return SbjgUtils.packageResponseStr(
        //                    "",
        //                    "",
        //                    "",
        //                    0,
        //                    allOcrFileResult,
        //                    null,
        //                    null,
        //                    true,
        //                    true
        //            );
        //        }
        throw new AppException("ocr识别失败");
    }
}
